package com.nineclock.auth.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");

        if (StrUtil.isEmpty(mobile) ) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        SysUserDTO userDTO = sysUserFeign.queryUser(mobile).getData();
        if (userDTO==null){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }

        String key= SMSConstant.SMS_LOGIN_KEY_PREFIX +mobile;
        String code=redisTemplate.boundValueOps(key).get();

        userDTO.setPassword(bCryptPasswordEncoder.encode(code));
        return userDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        return entity!=null&& entity.getAuthType()!=null&& "sms".equalsIgnoreCase(entity.getAuthType());
    }
}
